<?php

/**
 * Created by PhpStorm.
 * Script Name: Setting.php
 * Create: 2020/5/24 上午10:25
 * Description: 站点配置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\admin\controller;

use app\admin\model\BotGroupmember;
use app\admin\model\BotMember;
use app\common\model\Forward as ForwardM;
use app\constants\Bot;
use app\constants\Common;

class Forward extends Botbase
{
    /**
     * @var ForwardM
     */
    protected $model;
    /**
     * @var BotGroupmember
     */
    private $groupMemberM;
    /**
     * @var BotMember
     */
    private $memberM;
    /**
     * @var array
     */
    private $tabList;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new ForwardM();
        $this->groupMemberM = new BotGroupmember();
        $this->memberM = new BotMember();
        $this->tabList = [
            'group' => ['title' => '新增群聊转播', 'href' => url('add', ['type' => 'group'])],
            'private' => ['title' => '新增私聊转播', 'href' => url('add', ['type' => 'private'])],
        ];
    }

    /**
     *
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function index()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = ['g.bot_id' => $this->bot['id'], 'g.admin_id' => $this->adminInfo['id']];
            $params = [
                'alias' => 'g',
                'join' => [
                    ['bot_member m', 'm.id=g.group_id', 'left']
                ],
                'where' => $where,
                'refresh' => true
            ];
            $total = $this->model->totalJoin($params);
            if ($total) {
                $list = $this->model->getListJoin(array_merge($params, [
                    'limit' => [$post_data['page'], $post_data['limit']],
                    'field' => ['g.id','m.nickname as group_title', 'g.officer', 'group_id','g.status','g.wxids','g.member_tags']
                ]));
                foreach ($list as $k => $v){
                    if($v['group_id']){
                        $group_members = $this->groupMemberM->getField(['nickname'], ['wxid' => ['in', $v['officer']], 'group_id' => $v['group_id']]);
                        $v['officer_names'] = implode(',', $group_members);
                    }else{
                        $v['group_title'] = '---';
                        if($officer = $this->memberM->getOneByMap(['wxid' => $v['officer']],['nickname'])){
                            $v['officer_names'] = $officer['nickname'];
                        }else{
                            $v['officer_names'] = '---';
                        }
                    }

                    if($v['wxids']){
                        $ids = explode(',', $v['wxids']);
                        if($member = model('admin/botMember')->getOneByMap([
                            'wxid' => $ids[0]
                        ])){
                            $v['wxids'] = $member['nickname'];
                            if(count($ids) > 1){
                                $v['wxids'] .= "等".count($ids)."个对象";
                            }
                        }else{
                            $v['wxids'] = "--";
                        }
                    }else{
                        $v['wxids'] = '用户分组：' . $v['member_tags'];
                    }
                    $list[$k] = $v;
                }
            }else{
                $list = [];
            }
            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }
        $builder = new ListBuilder();
        $builder->addTopButton('addnew', ['title' => '新增转播'])
                ->addTableColumn(['title' => '序号', 'field' => 'id', 'type' => 'index','minWidth' => 70])
                ->addTableColumn(['title' => '主讲群', 'field' => 'group_title', 'minWidth' => 150])
                ->addTableColumn(['title' => '主讲人', 'field' => 'officer_names', 'minWidth' => 200])
                ->addTableColumn(['title' => '发送对象', 'field' => 'wxids', 'minWidth' => 200])
                ->addTableColumn(['title' => '状态', 'field' => 'status', 'type' => 'switch', 'options' => Common::status(),'minWidth' => 60])
                ->addTableColumn(['title' => '操作', 'minWidth' => 70, 'type' => 'toolbar'])
                ->addRightButton('edit')
                ->addRightButton('delete');
        return $builder->show();
    }

    private function getOfficers(){
        $groups = $this->memberM->getAll([
            'where' => ['uin' => $this->bot['uin'], 'type' => Bot::GROUP],
            'field' => ['id','nickname as title']
        ]);
        foreach ($groups as $k => $v){
            $v['children'] = $this->groupMemberM->getAll([
                'where' => ['group_id' => $v['id']],
                'field' => ['wxid as id','nickname as title']
            ]);
            $groups[$k] = $v;
        }
        return $groups;
    }

    public function add(){
        $type = input('type', 'group');
        $data = ['bot_id' => $this->bot['id'], 'status' => 1];
        $builder = new FormBuilder();
        $builder->setPostUrl(url('savePost'))
            ->setTabNav($this->tabList, $type)
            ->addFormItem('bot_id', 'hidden', 'bot_id', 'bot_id')
            ->addFormItem('status', 'radio', '转发状态', '转发状态', [1=>'转发', 0 => '暂停'], 'required');
        if($type == 'private'){
            $builder->addFormItem('officer', 'chosen', '主讲人', '选择主讲人', $this->getMembers(['type' => Bot::FRIEND]), 'required');
        }else{
            $builder->addFormItem('officer', 'linkage', '主讲群&人', '选择主讲人', ['data' => $this->getOfficers()], 'required');
        }
        $builder->addFormItem('zddx_legend', 'legend', '指定对象', '指定对象')
            ->addFormItem('member_tags', 'chosen_multi', '用户分组', '用户分组', model('memberTag')->getTitleToTitle($this->bot['id']))
            ->addFormItem('wxids', 'chosen_multi', '自由选择', '若填此项则用户分组的设置将失效', $this->getMembers())
            ->setFormData($data);
        return $builder->show();
    }

    public function edit(){
        $id = input('id', null);
        $data = $this->model->getOne($id);

        if (!$data) {
            $this->error('参数错误');
        }

        $data['wxids'] = empty($data['wxids']) ? [] : explode(',', $data['wxids']);
        $data['member_tags'] = empty($data['member_tags']) ? [] : explode(',', $data['member_tags']);

        $builder = new FormBuilder();
        $builder->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'id', 'id')
            ->addFormItem('status', 'radio', '转发状态', '转发状态', [1=>'转发', 0 => '暂停'], 'required');
        if(! $data['group_id']){
            $builder->addFormItem('officer', 'chosen', '主讲人', '选择主讲人', $this->getMembers(['type' => Bot::FRIEND]), 'required');
        }else{
            $builder->addFormItem('officer', 'linkage', '主讲人&群', '选择主讲人', ['data' => $this->getOfficers(), 'values' => [$data['group_id'], $data['officer']]], 'required');
        }
        $builder->addFormItem('zddx_legend', 'legend', '指定对象', '指定对象')
            ->addFormItem('member_tags', 'chosen_multi', '用户分组', '用户分组', model('memberTag')->getTitleToTitle($this->bot['id']))
            ->addFormItem('wxids', 'chosen_multi', '自由选择', '若填此项则用户分组的设置将失效', $this->getMembers())
            ->setFormData($data);
        return $builder->show();
    }

    public function savePost($jump_to = '/undefined', $data = [])
    {
        $post_data = input('post.');
        $post_data['admin_id'] = $this->adminInfo['id'];
        if(strpos($post_data['officer'], ',') !== false){
            list($group_id, $officer) = explode(',', $post_data['officer']);
            $post_data['group_id'] = $group_id;
            $post_data['officer'] = $officer;
        }
        if(empty($post_data[$this->pk])){
            $res = $this->model->addOne($post_data);
        }else {
            $res = $this->model->updateOne($post_data);
        }
        if($res){
            if(!empty($res['group_id'])){
                $group = model('admin/botMember')->getOne($res['group_id']);
                $group_wxid = $group['wxid'];
            }else{
                $group_wxid = '';
            }
            $this->model->getGather([
                'group_wxid' => $group_wxid,
                'from_wxid' => $res['officer'],
                'bot_wxid' => $this->bot['uin'],
                'refresh' => true
            ]);
            $this->success('数据保存成功', $jump_to);
        }else{
            $this->error('数据保存出错');
        }
    }
}